package com.leyou.user.service.controller;

import com.leyou.user.entity.TbUser;
import com.leyou.user.service.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.Pattern;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    //验证用户名和手机号是否存在
    @GetMapping("check/{data}/{type}")
    public ResponseEntity<Boolean> checkUserData(@PathVariable("data")String data,@PathVariable(name="type")Integer type){
        Boolean bool = userService.checkUserData(data, type);
        if(bool==null){
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(bool);
    }

    //发送验证码
    @PostMapping("send")
    public ResponseEntity<Void> sendVerifyCode(@Pattern(regexp = "^1[35678]\\d{9}$",message = "手机格式有误") String phone){
        Boolean bool = userService.sendVerifyCode(phone);
        if(bool==null){
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return ResponseEntity.ok().build();
    }

    public static void main(String[] args) {
        String s="^1[35678]\\d{9}$";
        System.out.println(java.util.regex.Pattern.matches(s, "15517901032"));
    }

    /**
     * 注册用户信息
     * @param user
     * @param code
     * @return
     */
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid TbUser user, String code){
        Boolean bool = userService.register(user, code);
        if(bool==null || !bool){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    /**
     * 查询用户和密码是否存在
     */
    @GetMapping("query")
    public ResponseEntity<TbUser> queryUser(String username,String password){
        TbUser tbUser = userService.queryUser(username, password);
        if(tbUser==null){
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(tbUser);
    }



}
